<template>
  <div class="sale-pet-manage-container">
    <h1 class="page-title">🐈 待售宠物信息管理</h1>

    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="宠物名称">
          <el-input v-model="searchForm.petName" placeholder="请输入宠物名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="狗" :value="1"></el-option>
            <el-option label="猫" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品种">
          <el-input v-model="searchForm.breed" placeholder="请输入品种" clearable></el-input>
        </el-form-item>
        <el-form-item label="销售状态">
          <el-select v-model="searchForm.saleStatus" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="待售" :value="1"></el-option>
            <el-option label="已预定" :value="2"></el-option>
            <el-option label="已售出" :value="3"></el-option>
            <el-option label="已下架" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格范围">
          <el-input-number v-model="searchForm.minPrice" :min="0" placeholder="最低" controls-position="right" style="width: 130px;"></el-input-number>
          <span style="margin: 0 10px;">-</span>
          <el-input-number v-model="searchForm.maxPrice" :min="0" placeholder="最高" controls-position="right" style="width: 130px;"></el-input-number>
        </el-form-item>
        <el-form-item label="折扣范围(%)">
          <el-input-number v-model="searchForm.minDiscount" :min="0" :max="100" placeholder="最低" controls-position="right" style="width: 130px;"></el-input-number>
          <span style="margin: 0 10px;">-</span>
          <el-input-number v-model="searchForm.maxDiscount" :min="0" :max="100" placeholder="最高" controls-position="right" style="width: 130px;"></el-input-number>
        </el-form-item>
        <el-form-item label="浏览量">
          <el-input-number v-model="searchForm.minViewCount" :min="0" placeholder="最少" controls-position="right" style="width: 150px;"></el-input-number>
        </el-form-item>
        <el-form-item label="点赞数">
          <el-input-number v-model="searchForm.minLikeCount" :min="0" placeholder="最少" controls-position="right" style="width: 150px;"></el-input-number>
        </el-form-item>
        <el-form-item label="推荐">
          <el-select v-model="searchForm.isRecommended" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="是" :value="true"></el-option>
            <el-option label="否" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="热销">
          <el-select v-model="searchForm.isHot" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="是" :value="true"></el-option>
            <el-option label="否" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上架日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="排序">
          <el-select v-model="searchForm.orderBy" placeholder="排序字段" clearable style="width: 120px;">
            <el-option label="默认" value=""></el-option>
            <el-option label="价格" value="price"></el-option>
            <el-option label="浏览量" value="viewCount"></el-option>
            <el-option label="点赞数" value="likeCount"></el-option>
            <el-option label="更新时间" value="updateTime"></el-option>
          </el-select>
          <el-select v-model="searchForm.order" placeholder="排序方向" style="width: 100px; margin-left: 10px;">
            <el-option label="降序" value="desc"></el-option>
            <el-option label="升序" value="asc"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增待售宠物</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 待售宠物列表 -->
    <el-card style="margin-top: 20px;">
      <el-table :data="salePetList" v-loading="loading" stripe>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="图片" width="80">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.image"
              :preview-src-list="[scope.row.image]"
              style="width: 50px; height: 50px; border-radius: 4px;">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="breed" label="品种"></el-table-column>
        <el-table-column prop="age" label="年龄">
          <template slot-scope="scope">
            {{ scope.row.age }}个月
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="price" label="售价">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" label="原价">
          <template slot-scope="scope">
            <span style="text-decoration: line-through; color: #999;">¥{{ scope.row.originalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="saleStatus" label="销售状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getSaleStatusType(scope.row.saleStatus)">{{ scope.row.saleStatusName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="浏览量" width="100"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="160"></el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button size="mini" type="warning" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-dropdown @command="(cmd) => handleCommand(cmd, scope.row)" style="margin-left: 10px;">
              <el-button size="mini">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="status" v-if="scope.row.saleStatus === 'onsale'">
                  下架
                </el-dropdown-item>
                <el-dropdown-item command="status" v-else-if="scope.row.saleStatus === 'offsale'">
                  上架
                </el-dropdown-item>
                <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog title="宠物详情" :visible.sync="viewDialogVisible" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="宠物名称">{{ viewPetData.petName || viewPetData.name }}</el-descriptions-item>
        <el-descriptions-item label="品种">{{ viewPetData.breed }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ viewPetData.categoryName }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ viewPetData.genderText || viewPetData.gender }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ viewPetData.age }}个月</el-descriptions-item>
        <el-descriptions-item label="原价">¥{{ viewPetData.originalPrice }}</el-descriptions-item>
        <el-descriptions-item label="售价">
          <span class="price">¥{{ viewPetData.price }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="销售状态">
          <el-tag :type="getSaleStatusType(viewPetData.petStatus)">{{ viewPetData.petStatusText }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="健康状况">{{ viewPetData.healthStatusText }}</el-descriptions-item>
        <el-descriptions-item label="疫苗情况">{{ viewPetData.vaccinationStatusText }}</el-descriptions-item>
        <el-descriptions-item label="绝育情况">{{ viewPetData.sterilizationStatusText }}</el-descriptions-item>
        <el-descriptions-item label="浏览量">{{ viewPetData.viewCount }}</el-descriptions-item>
        <el-descriptions-item label="详细描述" :span="2">{{ viewPetData.description || '无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ viewPetData.createTime }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer">
        <el-button type="primary" @click="viewDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="750px">
      <el-form :model="salePetForm" :rules="salePetRules" ref="salePetForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="宠物名称" prop="name">
              <el-input v-model="salePetForm.name" placeholder="请输入宠物名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-input v-model="salePetForm.type" placeholder="请输入类型"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品种" prop="breed">
              <el-input v-model="salePetForm.breed" placeholder="请输入品种"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="salePetForm.age" :min="0" :max="300" style="width: 100%"></el-input-number>
              <span style="margin-left: 10px">个月</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="salePetForm.gender">
                <el-radio label="公">公</el-radio>
                <el-radio label="母">母</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="颜色">
              <el-input v-model="salePetForm.color" placeholder="请输入颜色"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input v-model.number="salePetForm.originalPrice" placeholder="请输入原价">
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售价" prop="price">
              <el-input v-model.number="salePetForm.price" placeholder="请输入售价">
                <template slot="prepend">¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="疫苗情况">
          <el-input v-model="salePetForm.vaccine" placeholder="请输入疫苗情况"></el-input>
        </el-form-item>

        <el-form-item label="健康状况">
          <el-input v-model="salePetForm.health" placeholder="请输入健康状况"></el-input>
        </el-form-item>

        <el-form-item label="详细描述">
          <el-input type="textarea" v-model="salePetForm.description"
                    :rows="3" placeholder="请输入宠物详细描述"></el-input>
        </el-form-item>

        <el-form-item label="图片上传">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminSalePetList } from '@/api/salePet'
import salePetApi from '@/api/salePet'

export default {
  name: 'SalePetManage',
  data () {
    return {
      searchForm: {
        petName: '',
        categoryId: null,
        breed: '',
        saleStatus: null,
        minPrice: null,
        maxPrice: null,
        minDiscount: null,
        maxDiscount: null,
        minViewCount: null,
        minLikeCount: null,
        isRecommended: null,
        isHot: null,
        dateRange: null,
        orderBy: '',
        order: 'desc'
      },
      salePetList: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      viewDialogVisible: false,
      viewPetData: {},
      dialogTitle: '新增待售宠物',
      salePetForm: {
        name: '',
        type: '',
        breed: '',
        age: 0,
        gender: '公',
        color: '',
        originalPrice: 0,
        price: 0,
        vaccine: '',
        health: '',
        description: ''
      },
      salePetRules: {
        name: [{ required: true, message: '请输入宠物名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        breed: [{ required: true, message: '请输入品种', trigger: 'blur' }],
        originalPrice: [{ required: true, message: '请输入原价', trigger: 'blur' }],
        price: [{ required: true, message: '请输入售价', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.loadSalePetList()
  },
  methods: {
    async loadSalePetList () {
      this.loading = true
      try {
        // 构建查询参数
        const params = {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        }
        
        // 添加筛选条件（只添加有值的参数）
        if (this.searchForm.petName) {
          params.petName = this.searchForm.petName
        }
        if (this.searchForm.categoryId !== null && this.searchForm.categoryId !== '') {
          params.categoryId = this.searchForm.categoryId
        }
        if (this.searchForm.breed) {
          params.breed = this.searchForm.breed
        }
        if (this.searchForm.saleStatus !== null && this.searchForm.saleStatus !== '') {
          params.saleStatus = this.searchForm.saleStatus
        }
        // 价格范围
        if (this.searchForm.minPrice !== null && this.searchForm.minPrice !== '') {
          params.minPrice = this.searchForm.minPrice
        }
        if (this.searchForm.maxPrice !== null && this.searchForm.maxPrice !== '') {
          params.maxPrice = this.searchForm.maxPrice
        }
        // 折扣范围
        if (this.searchForm.minDiscount !== null && this.searchForm.minDiscount !== '') {
          params.minDiscount = this.searchForm.minDiscount
        }
        if (this.searchForm.maxDiscount !== null && this.searchForm.maxDiscount !== '') {
          params.maxDiscount = this.searchForm.maxDiscount
        }
        // 浏览量和点赞数
        if (this.searchForm.minViewCount !== null && this.searchForm.minViewCount !== '') {
          params.minViewCount = this.searchForm.minViewCount
        }
        if (this.searchForm.minLikeCount !== null && this.searchForm.minLikeCount !== '') {
          params.minLikeCount = this.searchForm.minLikeCount
        }
        // 推荐和热销
        if (this.searchForm.isRecommended !== null) {
          params.isRecommended = this.searchForm.isRecommended
        }
        if (this.searchForm.isHot !== null) {
          params.isHot = this.searchForm.isHot
        }
        // 日期范围
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startDate = this.searchForm.dateRange[0]
          params.endDate = this.searchForm.dateRange[1]
        }
        // 排序
        if (this.searchForm.orderBy) {
          params.orderBy = this.searchForm.orderBy
          params.order = this.searchForm.order
        }
        
        console.log('待售宠物查询参数:', params)
        const res = await getAdminSalePetList(params)
        console.log('待售宠物返回数据:', res)
        // 处理响应数据
        const data = (res.data && res.data.records) || (res.data && res.data.list) || res.data || []
        this.salePetList = data.map(item => ({
          id: item.id,
          name: item.petName || item.pet_name || item.name || '未命名',
          breed: item.breed || '未知品种',
          age: item.age || 0,
          gender: item.genderText || item.gender_text || this.getGenderText(item.gender),
          price: item.price || 0,
          originalPrice: item.originalPrice || item.original_price || 0,
          image: item.mainImage || item.main_image || item.image || require('@/assets/logo.png'),
          saleStatus: item.saleStatus || item.petStatus,
          saleStatusName: item.saleStatusText || item.sale_status_text || this.getPetStatusText(item.saleStatus || item.petStatus),
          viewCount: item.viewCount || item.view_count || 0,
          likeCount: item.likeCount || item.like_count || 0,
          updateTime: item.updateTime || item.update_time || ''
        }))
        this.pagination.total = (res.data && res.data.total) || data.length || 0
      } catch (error) {
        this.$message.error('加载失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.loadSalePetList()
    },
    handleReset () {
      this.searchForm = {
        petName: '',
        categoryId: null,
        breed: '',
        saleStatus: null,
        minPrice: null,
        maxPrice: null,
        minDiscount: null,
        maxDiscount: null,
        minViewCount: null,
        minLikeCount: null,
        isRecommended: null,
        isHot: null,
        dateRange: null,
        orderBy: '',
        order: 'desc'
      }
      this.pagination.currentPage = 1
      this.loadSalePetList()
    },
    handleAdd () {
      this.dialogTitle = '新增待售宠物'
      this.salePetForm = {
        name: '',
        type: '',
        breed: '',
        age: 0,
        gender: '公',
        color: '',
        originalPrice: 0,
        price: 0,
        vaccine: '',
        health: '',
        description: ''
      }
      this.dialogVisible = true
    },
    async handleView (row) {
      try {
        const res = await salePetApi.getSalePetDetail(row.id)
        const data = res.data || row
        this.viewPetData = {
          ...data,
          genderText: this.getGenderText(data.gender),
          petStatusText: this.getPetStatusText(data.petStatus),
          healthStatusText: this.getHealthStatusText(data.healthStatus),
          vaccinationStatusText: this.getVaccinationStatusText(data.vaccinationStatus),
          sterilizationStatusText: this.getSterilizationStatusText(data.sterilizationStatus),
          createTime: this.formatDate(data.createTime)
        }
        this.viewDialogVisible = true
      } catch (error) {
        this.$message.error('加载详情失败：' + (error.message || '未知错误'))
      }
    },
    async handleEdit (row) {
      try {
        const res = await salePetApi.getSalePetDetail(row.id)
        const data = res.data
        this.dialogTitle = '编辑待售宠物'
        this.salePetForm = {
          id: data.id,
          name: data.petname || data.petName || data.name,
          type: data.categoryname || data.categoryName || data.type,
          breed: data.breed,
          age: data.age,
          gender: data.gendertext || data.genderText || '公',
          color: data.color,
          originalPrice: data.originalprice || data.originalPrice,
          price: data.price,
          vaccine: data.vaccine || data.vaccinationstatustext || data.vaccinationStatusText,
          health: data.health || data.healthstatustext || data.healthStatusText,
          description: data.description
        }
        this.dialogVisible = true
      } catch (error) {
        this.$message.error('加载详情失败：' + (error.message || '未知错误'))
      }
    },
    handleCommand (command, row) {
      if (command === 'status') {
        const action = row.saleStatus === 'onsale' ? '下架' : '上架'
        const newStatus = row.saleStatus === 'onsale' ? 'offsale' : 'onsale'
        this.$confirm(`确认${action}该宠物吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await salePetApi.updateSalePetStatus(row.id, newStatus)
            this.$message.success(`${action}成功`)
            this.loadSalePetList()
          } catch (error) {
            this.$message.error(`${action}失败：` + (error.message || '未知错误'))
          }
        })
      } else if (command === 'delete') {
        this.$confirm(`确认删除宠物 "${row.name}" 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await salePetApi.deleteSalePet(row.id)
            this.$message.success('删除成功')
            this.loadSalePetList()
          } catch (error) {
            this.$message.error('删除失败：' + (error.message || '未知错误'))
          }
        })
      }
    },
    handleSubmit () {
      this.$refs.salePetForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.salePetForm.id) {
              await salePetApi.updateSalePet(this.salePetForm.id, this.salePetForm)
            } else {
              await salePetApi.addSalePet(this.salePetForm)
            }
            this.$message.success('操作成功')
            this.dialogVisible = false
            this.loadSalePetList()
          } catch (error) {
            this.$message.error('操作失败：' + (error.message || '未知错误'))
          }
        }
      })
    },
    getSaleStatusType (status) {
      const typeMap = {
        'onsale': 'success',
        'reserved': 'warning',
        'sold': 'info',
        'offsale': 'danger'
      }
      return typeMap[status] || 'info'
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.loadSalePetList()
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.loadSalePetList()
    },
    // 字段映射方法
    mapPetStatus (status) {
      const statusMap = { 1: 'onsale', 2: 'sold', 3: 'adopted', 4: 'reserved' }
      return statusMap[status] || 'onsale'
    },
    getPetStatusText (status) {
      const textMap = { 1: '待售', 2: '已售', 3: '已被领养', 4: '已预定' }
      return textMap[status] || '待售'
    },
    getGenderText (gender) {
      return gender === 1 ? '雄性' : gender === 2 ? '雌性' : '未知'
    },
    getHealthStatusText (status) {
      const textMap = { 1: '健康', 2: '一般', 3: '需要关注' }
      return textMap[status] || '未知'
    },
    getVaccinationStatusText (status) {
      return status === 1 ? '已接种' : '未接种'
    },
    getSterilizationStatusText (status) {
      return status === 1 ? '已绝育' : '未绝育'
    },
    formatDateTime (dateTime) {
      if (!dateTime) return '-'
      return dateTime.replace('T', ' ').substring(0, 19)
    },
    formatDate (dateTime) {
      if (!dateTime) return '-'
      return dateTime.split('T')[0]
    }
  }
}
</script>

<style scoped>
.sale-pet-manage-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>
